/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.Tools;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.institution.approval.LawAddService;
import com.koron.institution.approval.LawEditService;
import com.koron.institution.bean.*;
import com.koron.institution.mapper.LawHistoryMapper;
import com.koron.institution.mapper.LawMapper;
import com.koron.institution.service.api.LawService;
import com.koron.institution.uitls.BaseEntityUtil;
import com.koron.institution.uitls.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

import static com.koron.institution.uitls.ExcelUtil.getCellValue;

@Service
@PropertySource("classpath:institution.properties")
public class LawServiceImpl implements LawService, InitializingBean, AfterApprovalService {

    private final static  Logger logger = LoggerFactory.getLogger(Logger.class);

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Value("${law_add_confirm}")
    private String lawAddConfirm;

    @Value("${law_discard_confirm}")
    private String lawDiscardConfirm;

    @Value("${law_edit_confirm}")
    private String lawEditConfirm;

    @Value("${institution_file_template_key}")
    private String institutionFileTemplateKey;

    @Value("${law_institution_file_template_key}")
    private String lawInstitutionFileTemplateKey;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Override
    public MessageBean<?> getList(StaffBean user, String fileName, String lawItem, String categoryId, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        SessionFactory factory = new SessionFactory();
        try {
            LawMapper mapper = factory.getMapper(LawMapper.class);
            Integer start = null;
            if (null != page && page > 0 && null != pageSize && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            List<Law> list = mapper.getLawListByCondition(fileName, lawItem, categoryId, start, pageSize);
            Integer total = mapper.getTotalBycondition(fileName, lawItem, categoryId);
            // 获取满足条件的法规条款
            if (null != list && list.size() > 0) {
                list.forEach(law -> {
                    List<LawItem> itemList = mapper.getLawItem(law.getId(), lawItem);
                    law.setLawItemList(itemList);
                });

            }
            // 判断当前登录用户是不是管理员
            if (("admin").equals(user.getUserid())) {
                list.forEach(law -> law.setIsAdmin(true));
            } else {
                list.forEach(law -> law.setIsAdmin(false));
            }
            DataBean<Law> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 1 : total > pageSize ? total % pageSize == 0 ? total / pageSize : total / pageSize + 1 : 1);
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }


    @Override
    public MessageBean<?> getAll(StaffBean user, String lawItem, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        SessionFactory factory = new SessionFactory();
        try {
            LawMapper mapper = factory.getMapper(LawMapper.class);
            Integer start = null;
            Integer end = null;
            DataBean<Law> dataBean = new DataBean<>();
            if (null != page && page > 0 && null != pageSize && pageSize > 0) {
                start = (page - 1) * pageSize;
                end = start + pageSize;
            }
            // 获取所有文件名符合条件的法规id
            List<String> idList = mapper.getIdsInLaw(lawItem);
            // 获取所有法规条款符合条件的法规id
            List<String> idList1 = mapper.getIdsInLawItem(lawItem);

            List<String> idList2 = mapper.getIdsInCategoryName(lawItem);
            //去除所有法规条款符合条件中重复的id
            idList.forEach(id -> {
                if (idList1.contains(id)) {
                    idList1.remove(id);
                }
                if (idList2.contains(id)) {
                    idList2.remove(id);
                }
            });
            List<Law> list = new ArrayList<>();
            // 优先查询文件名符合条件的法规
//            if (null != end && idList.size() >= end) {
//                // 在查询数量范围内，全是文件名符合条件的数量
//                if (idList.size() > 0) {
//                    list = mapper.getAllByCondition(idList, start, pageSize);
//                }
//            } else if (null != start && null != end && idList.size() >= start && idList.size() <= end) {
//                // 在查询数量范围内，有部分文件名符合条件的数据
//                if (idList.size() > 0) {
//                    list = mapper.getAllByCondition(idList, start, pageSize);
//                }
//                if (idList1.size() > 0) {
//                    int num = end - idList.size();
//                    List<Law> list1 = mapper.getAllByCondition(idList1, 0, num);
//                    list.addAll(list1);
//                }
//            } else if (null != start && idList.size() < start) {
//                // 在查询数量范围内，没有文件名符合条件的数据
//                if (idList1.size() > 0) {
//                    Integer startNum = start - idList.size();
//                    list = mapper.getAllByCondition(idList1, startNum, pageSize);
//                }
//            }

            idList.addAll(idList1);
            idList.addAll(idList2);
            List<String> result = null;
            if (null != start && null != end && idList.size()>= start && idList.size() >= end){
                result = idList.subList(start,end);
            }else if (null != start && null != end && idList.size() >= start && idList.size() <= end){
                result = idList.subList(start,idList.size());
            }
            if(result != null && !result.isEmpty()) {
                Map<String, Law> collect = mapper.getAllByCondition(result, null, null).stream().collect(Collectors.toMap(p -> p.getId(), p -> p));
                //保证顺序
                result.forEach(s -> {
                    list.add(collect.get(s));
                });
            }
            // 获取满足条件的法规条款
            if (null != list && list.size() > 0) {
                list.forEach(law -> {
                    if (null != idList1 && idList1.size() > 0 && idList1.contains(law.getId())) {
                        List<LawItem> itemList = mapper.getLawItem(law.getId(), lawItem);
                        law.setLawItemList(itemList);
                    } else {
                        List<LawItem> itemList = mapper.getLawItem(law.getId(), lawItem);
                        if (null == itemList || itemList.size() == 0) {
                            itemList = mapper.getLawItem(law.getId(), null);
                        }
                        law.setLawItemList(itemList);
                    }
                });
            }
            dataBean.setList(list);
            Integer total = idList.size();
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 1 : total > pageSize ? total % pageSize == 0 ? total / pageSize : total / pageSize + 1 : 1);
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<?> save(String lawStr, StaffBean user, MultipartFile[] file) {
        MessageBean<InstitutionFile> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), InstitutionFile.class);
        SessionFactory factory = new SessionFactory();
        try {
            Law law = JSONObject.parseObject(lawStr, Law.class);
            if (law == null) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(law.getCategoryId())) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(law.getFileName())) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_FILE_NAME.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_FILE_NAME.getDescription());
                return msg;
            }
            LawMapper mapper = factory.getMapper(LawMapper.class);
            //检测是否重复
            Integer check = mapper.cheak(law.getFileName(), law.getFileCode(), law.getCategoryId(), law.getId());
            if (check > 0) {
                factory.close(false);
                msg.setCode(BusinessCode.INSTITUTION_EXIST.getCode());
                msg.setDescription(BusinessCode.INSTITUTION_EXIST.getDescription());
                return msg;
            }
            //保存附件；
            List<String> keepAddressList = new ArrayList<>();
            List<String> keepPreAddressList = new ArrayList<>();
            if (StringUtils.isNotBlank(law.getKeepAddressStr())) {
                String[] keepAddressArray = law.getKeepAddressStr().split("[,，]");
                keepAddressList.addAll(Arrays.asList(keepAddressArray));
            }
            if (StringUtils.isNotBlank(law.getKeepPreAddressStr())) {
                String[] keepPreAddressArray = law.getKeepPreAddressStr().split("[,，]");
                keepPreAddressList.addAll(Arrays.asList(keepPreAddressArray));
            }
            if (file != null && file.length > 0) {
                for (MultipartFile f : file) {
                    if (file != null) {
                        String url = clientWrapper.uploadFile(f);
                        String filPath = url + "#" + f.getOriginalFilename();
                        keepAddressList.add(filPath);
                        String pdfPath = docConverterUtils.converterUpdate(f);
                        if (pdfPath != null) {
                            keepPreAddressList.add(pdfPath);
                        } else {
                            keepPreAddressList.add(filPath);
                        }
                    }
                }
            }
            if (keepAddressList == null || keepAddressList.isEmpty()) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_ATTACHMENT.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_ATTACHMENT.getDescription());
                return msg;
            }
            law.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
            law.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
            if (StringUtils.isBlank(law.getId())) {
                //新增
                BaseEntityUtil.setAddBaseProperties(law, user);
                law.setCode(Tools.getCode32());
                mapper.insert(law);
            } else {
                //修改
                BaseEntityUtil.setUpdateBaseProperties(law, user);
                mapper.updateByPrimaryKeySelective(law);
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    LawHistory translateLawToHistory(Law law) {
        LawHistory history = new LawHistory();
        BeanUtils.copyProperties(law, history);
        return history;
    }

    @Override
    public MessageBean<?> discard(String lawId, StaffBean user, String approverCodeListStr) {
        MessageBean<Law> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Law.class);

        SessionFactory factory = new SessionFactory();
        try {
            LawMapper mapper = factory.getMapper(LawMapper.class);
            LawHistoryMapper historyMapper = factory.getMapper(LawHistoryMapper.class);
            //根据id获取制度记录
            Date now = new Date();
            Law law = mapper.selectByPrimaryKey(lawId);
            if (law == null) {
                msg.setCode(BusinessCode.INSTITUTION_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.INSTITUTION_NOT_EXIST.getDescription());
                factory.close();
                return msg;
            }
            if (law.getState() == 5) {
                mapper.deleteByPrimaryKey(law.getId());
                return msg;
            }
            if (StringUtils.isBlank(approverCodeListStr)) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                return msg;
            }
            List<String> approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
            if (approverCodeList == null || approverCodeList.isEmpty()) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                return msg;
            }
            law.setUpdateUser(user.getCode());
            law.setUpdateUserName(user.getName());
            law.setUpdateTime(now);
            law.setState(3);
            mapper.updateByPrimaryKeySelective(law);
            //添加一条审批记录
            LawHistory history = translateLawToHistory(law);
            history.setState(3);
            history.setHistoryFlag(1);
            history.setId(DefaultIdGenerator.getInstance().generateLongId());
            historyMapper.insert(history);
            //审批
            Audit audit = new Audit();

            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(2);
            audit.setTarget(LawAddService.class.getName());
            audit.setFlowName(lawDiscardConfirm);
            audit.setTitle(lawDiscardConfirm);
            audit.setCorpCode(law.getCorpCode());
            audit.setInitiatorCode(user.getCode());
            audit.setDescription(law.getFileName());
            audit.setState(1);
            audit.setTemplateKey(lawInstitutionFileTemplateKey);
            audit.setSetCode("institution_manage");
            audit.setInitiatorAccount(user.getUserid());
            List<String> idList = new ArrayList<>();
            idList.add(history.getId());
            audit.setBusinessIds(new Gson().toJson(idList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append(code.split("_")[0]).append(",");
            }
//            for (String code : approverCodeList) {
//                codes.append("1-").append(code.split("_")[0]).append(",");
//            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("废除法规提交审批失败");
            } else {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("废除法规提交审批成功");
                factory.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> delete(String lawId, StaffBean user) {
        MessageBean<Law> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Law.class);
        SessionFactory factory = new SessionFactory();
        try {
            LawMapper mapper = factory.getMapper(LawMapper.class);
            //根据id获取制度记录
            Law law = mapper.selectByPrimaryKey(lawId);
            if (law == null) {
                msg.setCode(BusinessCode.INSTITUTION_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.INSTITUTION_NOT_EXIST.getDescription());
                factory.close();
                return msg;
            }
            String attachment = law.getAttachment();
            String previewAttachment = law.getPreviewAttachment();
            Integer delete = mapper.delete(lawId);
            if (delete > 0) {
                // 删除法规下的条款
                mapper.deleteLawItemByLawId(lawId);
            }
            if (delete <= 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                return msg;
            }
            if (StringUtils.isNotEmpty(attachment)) {
                List<String> list = JSONObject.parseArray(attachment, String.class);
                list.forEach(url -> clientWrapper.deleteFile(url.split("#")[0]));
            }
            if (StringUtils.isNotEmpty(previewAttachment)) {
                List<String> list = JSONObject.parseArray(previewAttachment, String.class);
                list.forEach(url -> clientWrapper.deleteFile(url.split("#")[0]));
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }


    @Override
    public MessageBean<?> importFile(String categoryId, StaffBean user, MultipartFile[] files) {
        MessageBean<InstitutionFile> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), InstitutionFile.class);
        SessionFactory factory = new SessionFactory();
        List<String> addressList = new ArrayList<>();
        try {
            if (StringUtils.isBlank(categoryId)) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getDescription());
                return msg;
            }
            List<Law> lawList = new ArrayList<>();
            LawMapper mapper = factory.getMapper(LawMapper.class);
            if (files != null && files.length > 0) {
                // 循环遍历文件，将每一个文件生成一个法规数据
                for (MultipartFile file : files) {
                    Law law = new Law();
                    List<String> keepAddressList = new ArrayList<>();
                    List<String> keepPreAddressList = new ArrayList<>();
                    String filename = file.getOriginalFilename();
                    //获取文件原始名最后一个“.”号的位置
                    int indexOf = filename.lastIndexOf(".");
                    // 截取开始到最后一个.号作为法规名称
                    filename = filename.substring(0, indexOf);
                    law.setFileName(filename);
                    String url = clientWrapper.uploadFile(file);
                    String filPath = url + "#" + file.getOriginalFilename();
                    keepAddressList.add(filPath);
                    addressList.add(filPath);
                    String pdfPath = docConverterUtils.converterUpdate(file);
                    if (pdfPath != null) {
                        addressList.add(pdfPath);
                        keepPreAddressList.add(pdfPath);
                    } else {
                        keepPreAddressList.add(filPath);
                    }
                    law.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
                    law.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
                    lawList.add(law);
                }
            }
            if (null != lawList && lawList.size() > 0) {
                lawList.stream().forEach(law -> {
                    law.setCategoryId(categoryId);
                    law.setCode(Tools.getCode32());
                    try {
                        BaseEntityUtil.setAddBaseProperties(law, user);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                    }
                });
                mapper.batchInsert(lawList);
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            if (null != addressList && addressList.size() > 0) {
                addressList.forEach(url -> clientWrapper.deleteFile(url.split("#")[0]));
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }

    }

    @Override
    public MessageBean<?> importLawItem(String lawId, StaffBean user, MultipartFile file) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "导入成功", String.class);
        SessionFactory factory = new SessionFactory();
        List<LawItem> lawItemList = new ArrayList<>();
        try {
            InputStream inputStream = file.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                msg.setCode(BusinessCode.FAILURE.getCode());
                return msg;
            }
            // 获取excel表格行数
            int rows = sheet.getPhysicalNumberOfRows();
            // 获取法规版本，发布、实施日期数据
            LawMapper mapper = factory.getMapper(LawMapper.class);
            Law law = mapper.selectByPrimaryKey(lawId);
            if (null == law) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("法规不存在");
                return msg;
            }
            // 获取excel表单第二行数据，即为法规版本，发布、实施日期数据
            XSSFRow sheetRow = sheet.getRow(1);
            // 版本编号
            String version = getCellValue(sheetRow.getCell(0));
            law.setVersion(version);
            // 发布日期
            String publicationDateStr = getCellValue(sheetRow.getCell(1));
            Date publicationDate = getDate(publicationDateStr);
            if (null != publicationDate) {
                law.setPublicationDate(publicationDate);
            }
            // 实施日期
            String executionDateStr = getCellValue(sheetRow.getCell(2));
            Date executionDate = getDate(executionDateStr);
            if (null != executionDate) {
                law.setExecutionDate(executionDate);
            }
            // 更新法规数据
            law.setUpdateTime(new Date());
            mapper.updateByPrimaryKey(law);
            // 从第四行开始读取条款数据
            int order = 1;
            for (int i = 3; i < rows; i++) {
                LawItem item = new LawItem();
                XSSFRow row = sheet.getRow(i);
                if (null == row) {
                    continue;
                }
                String note1 = getCellValue(row.getCell(0));
                String note2 = getCellValue(row.getCell(1));
                String note3 = getCellValue(row.getCell(2));
                String note4 = getCellValue(row.getCell(3));
                if (!StringUtils.isEmpty(note1)) {
                    note1 = note1.replace(" ", "");
                    item.setNote1(note1);
                }
                if (!StringUtils.isEmpty(note2)) {
                    note2 = note2.replace(" ", "");
                    item.setNote2(note2);
                }
                if (!StringUtils.isEmpty(note3)) {
                    note3 = note3.replace(" ", "");
                    item.setNote3(note3);
                }
                if (!StringUtils.isEmpty(note4)) {
                    note4 = note4.replace(" ", "");
                    item.setNote4(note4);
                }
                if (!checkObjAllFieldsIsNull(item)) {
                    item.setSortNo(order);
                    lawItemList.add(item);
                }
                order++;
            }
            for (LawItem item : lawItemList) {
                item.setId(DefaultIdGenerator.getInstance().generateLongId());
                item.setLawId(lawId);
            }
            // 查询该条法规是否已经存在法规条款
            List<LawItem> itemList = mapper.queryLawItemByLawId(lawId);
            if (null != itemList && itemList.size() > 0) {
                //存在法规数据时，先删除原有的法规条款，再新增
                mapper.deleteLawItemByLawId(lawId);
            }
            if (null != lawItemList && lawItemList.size() > 0) {
                // 新增法规条款
                Integer value = mapper.batchInsertLawItem(lawItemList);
                if (value <= 0) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription(BusinessCode.FAILURE.getDescription());
                    return msg;
                }
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("导入失败");
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<?> getLawItems(SessionFactory factory, String fileName, String lawItem, Integer
            page, Integer pageSize) {
        MessageBean<DataBean> msg = new MessageBean<>();
        try {
            LawMapper mapper = factory.getMapper(LawMapper.class);
            Integer start = null;
            if (null != page && page > 0 && null != pageSize && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            List<Law> lawList = mapper.getLawList(fileName, lawItem);
            if (null != lawList && lawList.size() > 0) {
                List<String> lawIds = lawList.stream().map(law -> law.getId()).collect(Collectors.toList());
                // 获取法规详情
                List<LawItem> lawItems = mapper.getLawItems(lawIds, lawItem);
                lawList.forEach(law -> {
                    List<LawItem> lawItemList = lawItems.stream().filter(lawItem1 -> lawItem1.getLawId().equals(law.getId())).collect(Collectors.toList());
                    law.setLawItemList(lawItemList);
                });
            }
            List<Law> result = new ArrayList<>();
            List<Law> relation = new ArrayList<>();
            for (Law law : lawList) {
                if ((StringUtils.isNotEmpty(fileName) && law.getFileName().contains(fileName)) || (StringUtils.isNotEmpty(lawItem) && law.getFileName().contains(lawItem))) {
                    result.add(law);
                } else {
                    relation.add(law);
                }
            }
            result.addAll(relation);
            start = start == null ? 0 : start;
            Integer end = start == 0 ? pageSize : start + pageSize;
            if (end > result.size()) {
                end = result.size();
                if (start > end) {
                    start = end;
                }
            }
            // 获取存在搜索法规条款的法规
            /*List<Map> mapList = mapper.queryLawAndItemList(fileName, lawItem, start, pageSize);
            Set<Object> lawIds = mapList.stream().map(map -> map.get("lawId")).collect(Collectors.toSet());
            List<Map>result = new ArrayList<>();
            for (Object lawId : lawIds) {
                Map lawMap = new HashMap();
                List<Map>noteList = new ArrayList<>();
                mapList.forEach(map -> {
                    if (map.get("lawId").equals(lawId)){
                        Map note = new HashMap();
                        note.put("id",map.get("id"));
                        note.put("note1",map.get("note1"));
                        note.put("note2",map.get("note2"));
                        note.put("note3",map.get("note3"));
                        note.put("note4",map.get("note4"));
                        note.put("sortNo",map.get("sortNo"));
                        lawMap.put("lawId",lawId);
                        lawMap.put("fileName",map.get("fileName"));
                        lawMap.put("version",map.get("version"));
                        lawMap.put("publicationDate",map.get("publicationDate"));
                        lawMap.put("executionDate",map.get("executionDate"));
                        lawMap.put("category_name",map.get("category_name"));
                        noteList.add(note);
                    }
                });
                lawMap.put("noteList",noteList);
                result.add(lawMap);
            }
            Integer count = result.size();*/
//            Integer count = mapper.queryLawAndItemCount(fileName, lawItem);
//            DataBean<Map> dataBean = new DataBean<>();
            Integer count = result.size();
            DataBean<Law> dataBean = new DataBean<>();
            dataBean.setList(result.subList(start, end));
            dataBean.setTotalNumber(count);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 1 : count > pageSize ? count % pageSize == 0 ? count / pageSize : count / pageSize + 1 : 1);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }


    /**
     * 获取读取到excel中，有关时间的值
     *
     * @param dateStr
     * @return
     */
    public Date getDate(String dateStr) {
        Date date = null;
        if (StringUtils.isNotEmpty(dateStr)) {
            date = HSSFDateUtil.getJavaDate(Double.parseDouble(dateStr));
        }
        return date;
    }

    MessageBean<LawHistoryCond> checkAndProduceHistoryCond(String fileName, String version, Integer page, Integer
            pageSize) {
        MessageBean<LawHistoryCond> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), LawHistoryCond.class);
        LawHistoryCond cond = new LawHistoryCond();
        if (StringUtils.isNotBlank(fileName)) {
            cond.setFileName(fileName);
        }
        if (StringUtils.isNotBlank(version)) {
            cond.setVersion(version);
        }

        if (page != null && page > 0 && pageSize != null && pageSize > 0) {
            cond.setPage(page);
            cond.setPageSize(pageSize);
            cond.setStart((page - 1) * pageSize);
        }
        msg.setData(cond);
        return msg;
    }

    ;

    @Override
    public MessageBean<?> getHistoryList(String fileName, String corpCode, String version, Integer page, Integer
            pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            LawHistoryMapper historyMapper = factory.getMapper(LawHistoryMapper.class);
            MessageBean<LawHistoryCond> messageBean = checkAndProduceHistoryCond(fileName, version, page, pageSize);
            if (messageBean != null && messageBean.getCode() != 0) {
                return messageBean;
            }
            LawHistoryCond historyCond = messageBean.getData();
            historyCond.setHistoryFlag(1);
            List<LawHistory> list = historyMapper.getHistoryList(historyCond);
            int total = historyMapper.getTotal(historyCond);
            DataBean<LawHistory> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(historyCond.getPage());
            dataBean.setPageSize(historyCond.getPageSize());
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> getHistoryListByCode(String code, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            Integer start = null;
            if (page != null && page > 0 && pageSize != null && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            LawHistoryMapper historyMapper = factory.getMapper(LawHistoryMapper.class);
            List<LawHistory> list = historyMapper.getHistoryListByCode(code, pageSize, start);
            int total = historyMapper.countHistoryListByCode(code);
            DataBean<LawHistory> dataBean = new DataBean<>();
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            dataBean.setPageSize(pageSize);
            dataBean.setPageNo(page);
            dataBean.setTotalNumber(total);
            dataBean.setList(list);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> saveFile(MultipartFile[] files) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), String.class);
        try {
            List<String> keepAddressList = new ArrayList<>();
            if (files != null && files.length > 0) {
                String url = clientWrapper.uploadFile(files[0]);
                String filpath = url + "#" + files[0].getOriginalFilename();
                keepAddressList.add(filpath);

            }
            msg.setData((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> deleteFile(String filePaths) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), String.class);
        try {
            if (StringUtils.isNotEmpty(filePaths)) {
                String[] delAttArray = filePaths.split("[,，]");
                for (String att : delAttArray) {
                    clientWrapper.deleteFile(att.split("#")[0]);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    MessageBean<?> checkEditLaw(Law law, MessageBean msg, LawMapper mapper) {
        if (law == null) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(law.getCategoryId())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(law.getFileName())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_FILE_NAME.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_FILE_NAME.getDescription());
            return msg;
        }

        if (StringUtils.isBlank(law.getCorpCode())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
            return msg;
        }
        if (law.getPublicationDate() == null) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_PUBLICATION_DATE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_PUBLICATION_DATE.getDescription());
            return msg;
        }
        if (law.getExecutionDate() == null) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_EXECUTION_DATE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_EXECUTION_DATE.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(law.getCode())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CODE.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(law.getAttachment())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_ATTACHMENT.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_ATTACHMENT.getDescription());
            return msg;
        }

        List<Law> laws = mapper.queryLawByCode(law.getCode());
        if (laws == null || laws.size() == 0) {
            msg.setCode(BusinessCode.INSTITUTION_NOT_EXIST.getCode());
            msg.setDescription(BusinessCode.INSTITUTION_NOT_EXIST.getDescription());
            return msg;
        } else {
            if (laws.stream().anyMatch(institution -> !law.getCorpCode().equals(institution.getCorpCode()))) {
                msg.setCode(401);
                msg.setDescription("没有操作权限");
                return msg;
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> getProcessData(String ids) {
        MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory();) {
            if (StringUtils.isNotBlank(ids)) {
                List<String> idList = JSONObject.parseArray(ids, String.class);
                if (idList != null && !idList.isEmpty()) {
//                    InstitutionFileMapper mapper = factory.getMapper(InstitutionFileMapper.class);
//                    List<InstitutionFile> list = mapper.queryListByIds(idList);
                    LawHistoryMapper mapper = factory.getMapper(LawHistoryMapper.class);
                    List<LawHistory> list = mapper.queryListByIds(idList);
                    msg.setData(list);
                }
            } else {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_ID.getDescription());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }


    @Override
    public MessageBean<?> batchEdit(String corpCode, List<Law> lawList, StaffBean user, String
            approverCodeListStr) {
        MessageBean<?> msg = MessageBean.create(0, "success", Object.class);
        if (StringUtils.isBlank(corpCode)) {
            corpCode = user.getCode();
        }
        if (StringUtils.isBlank(approverCodeListStr)) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
            return msg;
        }
        List<String> approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
        if (approverCodeList == null || approverCodeList.isEmpty()) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            LawMapper mapper = factory.getMapper(LawMapper.class);
            LawHistoryMapper historyMapper = factory.getMapper(LawHistoryMapper.class);
            for (Law law : lawList) {
                List<String> keepAddressList = new ArrayList<>();
                List<String> keepPreAddressList = new ArrayList<>();
                if (StringUtils.isNotBlank(law.getKeepAddressStr())) {
                    String[] keepAddressArray = law.getKeepAddressStr().split("[,，]");
                    keepAddressList.addAll(Arrays.asList(keepAddressArray));
                }
                if (StringUtils.isNotBlank(law.getKeepPreAddressStr())) {
                    String[] keepPreAddressArray = law.getKeepPreAddressStr().split("[,，]");
                    keepPreAddressList.addAll(Arrays.asList(keepPreAddressArray));
                }
                if (law.getFiles() != null && !law.getFiles().isEmpty()) {
                    for (MultipartFile file : law.getFiles()) {
                        if (file != null) {
                            String url = clientWrapper.uploadFile(file);
                            String filPath = url + "#" + file.getOriginalFilename();
                            keepAddressList.add(filPath);
                            String pdfPath = docConverterUtils.converterUpdate(file);
                            if (pdfPath != null) {
                                keepPreAddressList.add(pdfPath);
                            } else {
                                keepPreAddressList.add(filPath);
                            }
                        }
                    }
                }
                law.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
                law.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
                checkEditLaw(law, msg, mapper);
                if (msg != null && msg.getCode() != 0) {
                    factory.close(false);
                    return msg;
                }
            }
            List<String> idList = new ArrayList<>();
            List<String> historyIdList = new ArrayList<>();
            Date now = new Date();
            for (Law law : lawList) {
                Law lawSameName = mapper.getLawByFileName(law);
                if (lawSameName != null && lawSameName.getCode() != null && !lawSameName.getCode().equals(law.getCode())) {
                    msg.setCode(BusinessCode.INSTITUTION_EXIST.getCode());
                    msg.setDescription(BusinessCode.INSTITUTION_EXIST.getDescription());
                    factory.close(false);
                    return msg;
                }
                Law orgLaw = mapper.selectByPrimaryKey(law.getId());

                //生成审批记录
                law.setAddTime(orgLaw.getAddTime());
                law.setAddUser(orgLaw.getAddUser());
                law.setAddTime(orgLaw.getAddTime());
                law.setState(2);
                BaseEntityUtil.setUpdateBaseProperties(law, user);
                LawHistory auditRecord = translateLawToHistory(law);
                auditRecord.setId(DefaultIdGenerator.getInstance().generateLongId());
                auditRecord.setState(2);
                auditRecord.setHistoryFlag(0);
                auditRecord.setNewLawId(orgLaw.getId());
                historyMapper.insert(auditRecord);
                //更新业务数据状态
                orgLaw.setState(2);
                mapper.updateByPrimaryKeySelective(orgLaw);
                historyIdList.add(auditRecord.getId());
                idList.add(law.getId());
            }
            // 构造audit
            Audit audit = new Audit();
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(1);
            audit.setTarget(LawEditService.class.getName());
            audit.setFlowName(lawEditConfirm);
            //audit.setTitle( snap.getUpdateUser() + "提交了一份随手拍待确认");
            audit.setTitle(lawEditConfirm);
            audit.setCorpCode(corpCode);
            audit.setInitiatorCode(user.getCode());
            audit.setDescription("法规制度修订");
            audit.setState(1);
            audit.setTemplateKey(lawInstitutionFileTemplateKey);
            audit.setSetCode("institution_manage");
            audit.setInitiatorAccount(user.getUserid());
            audit.setBusinessIds(new Gson().toJson(historyIdList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append(code.split("_")[0]).append(",");
            }
//            for (String code : approverCodeList) {
//                codes.append("1-").append(code.split("_")[0]).append(",");
//            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("提交法规制度失败");
            } else {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("提交法规制度成功");
                factory.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }


    /**
     * 判断对象及属性是否为空
     *
     * @param object
     * @return
     */
    public static boolean checkObjAllFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(LawAddService.class.getName(), new LawAddService());
        map.put(LawEditService.class.getName(), new LawEditService());
    }

    @Override
    public void editApproval(Audit audit) {

    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {

    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
